package entities;

import java.util.HashMap;
import java.util.Vector;

import utils.Debug;
import fragment.Fragment;

public class MMMEDirectory {
		
	private HashMap<String,MMME>MMMEList = new HashMap<String, MMME>();
	
	private synchronized void removeElement(String element){
		MMMEList.get(element).delete();
		MMMEList.remove(element);
		
		Debug.println("MMME Directory : removing element " + element);
	}
	
	public synchronized boolean contains(String elem){
		return MMMEList.containsKey(elem);
	}
	
	public synchronized Vector<Fragment> getListProducers(String element){
		if (this.contains(element))
			return MMMEList.get(element).getProducerList();
		else return new Vector<Fragment>();
	}
	
	public synchronized boolean isGivenByUser(String element){
	if (this.contains(element))
			return MMMEList.get(element).isGivenByUser();
		else return false;
	}
	
	public synchronized void addUserMMME(String element){
		if (this.contains(element))
				MMMEList.get(element).setGivenByUser(true);
		else{
			MMMEList.put(element, new MMME(element));
			Debug.println("MMME Directory : adding element " + element);
		}
	}
	
	public synchronized void removeUserMMME(String element){
		if (this.contains(element)){
			MMMEList.get(element).setGivenByUser(false);
			if(MMMEList.get(element).getProducerList().isEmpty()){
				Debug.println("MMME Directory : removing element " + element);
				removeElement(element);
			}
		}
	}
	
	public synchronized void registerNewGenerator(Fragment gen){

		for(String elem : gen.getGenerationCapabilities()){
			if (!(this.contains(elem))){
				MMMEList.put(elem, new MMME(elem,gen));
				Debug.println("MMME Directory : adding element " + elem);
			}
			MMMEList.get(elem).addProducer(gen);
		}
	}
	
	public synchronized void removeGenerator(Fragment gen){
		for(String s : gen.getGenerationCapabilities()){
			MMMEList.get(s).removeProducer(gen);
			if(MMMEList.get(s).getProducerList().isEmpty() && !MMMEList.get(s).isGivenByUser())
				removeElement(s);
		}
	}
	
	public synchronized HashMap<String,MMME> getMMMEList(){
		return MMMEList;
	}
}